package com.ddh.codeduck.infra.minio.config;

import io.minio.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
@ConditionalOnProperty(name = "minio.endpoint") // 只有当配置存在时才创建bean
public class MinioConfig {

    @Value("${minio.endpoint:}")
    private String endpoint;

    @Value("${minio.access-key:}")
    private String accessKey;

    @Value("${minio.secret-key:}")
    private String secretKey;

    @Value("${minio.bucket-name:default-bucket}")
    private String bucketName;

    @Bean
    public MinioClient minioClient() {
        if (endpoint.isEmpty() || accessKey.isEmpty() || secretKey.isEmpty()) {
            throw new IllegalStateException("MinIO 配置不完整，请检查配置文件");
        }
        return MinioClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();
    }

    @Bean
    public boolean initBucket(MinioClient minioClient) {
        try {
            // 检查存储桶是否存在
            boolean found = minioClient.bucketExists(
                    BucketExistsArgs.builder().bucket(bucketName).build()
            );
            if (!found) {
                // 创建存储桶
                minioClient.makeBucket(
                        MakeBucketArgs.builder().bucket(bucketName).build()
                );
                log.info("Bucket '{}' created successfully.", bucketName);
            } else {
                log.info("Bucket '{}' already exists.", bucketName);
            }
            return true;
        } catch (Exception e) {
            log.error("Failed to initialize bucket", e);
            return false;
        }
    }
}
